package com.mazaiting;

import cn.hutool.core.util.ObjectUtil;
import com.mazaiting.classfile.ClassFile;
import com.mazaiting.classfile.attr.MemberInfo;
import com.mazaiting.classpath.ClassResponse;
import com.mazaiting.classpath.Classpath;
import com.mazaiting.rtda.heap.MtClass;
import com.mazaiting.rtda.heap.MtClassloader;
import com.mazaiting.rtda.heap.MtMethod;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * 应用启动类
 * 测试参数:
 * -cp /Users/mazaiting/Data/program/gitee/simple-jvm/code/example/build/classes/java/main/ com.mazaiting.ch06.MyObject
 * 或
 * -cp /Users/mazaiting/Data/program/gitee/simple-jvm/code/example/build/classes/java/main/ com.mazaiting.ch05.GaussTest
 * @author mazaiting
 * @since 2021/8/10
 */
@Slf4j
public class SJava {
    public static void main(String[] args) {

        Cmd cmd = Cmd.parseCmd(args);
        if (cmd.isVersionFlag()) {
            System.out.println("version 0.0.1");
        } else if (cmd.isHelpFlag()) {
            log.info("Usage: {} [-options] class [args...]", SJava.class.getSimpleName());
        } else {
            startJVM(cmd);
        }
    }

    /**
     * 启动 JVM
     *
     * @param cmd 命令行参数
     */
    private static void startJVM(Cmd cmd) {
        // 解析
        Classpath classpath = new Classpath(cmd.getXjreOption(), cmd.getCpOption());
        log.info("classpath:{} class:{} args:{}\n", classpath, cmd.getClassName(), cmd.getArgs());
        // 创建类加载器
        MtClassloader classloader = new MtClassloader(classpath);
        // 替换类中的 .
        String className = cmd.getClassName().replace(".", "/");
        // 加载类
        MtClass mainClass = classloader.loadClass(className);
        MtMethod mainMethod = mainClass.getMainMethod();
        if (ObjectUtil.isNotNull(mainMethod)) {
            Interpreter.interpret(mainMethod);
        } else {
            log.debug("Main method not found in class {}", className);
        }
    }
}


















